package com.demon.androidbasic.widget.utils

import android.app.Activity
import android.content.Context
import android.graphics.drawable.BitmapDrawable
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow

/**
 * PopupWindow
 * Created by liyingchun on 2016/10/22.
 */
object PopupWindowUtil {
  /**
   * 初始化对话框
   *
   * @param view 自定义布局
   * @param activity 类
   * @return 对话框
   */
  fun initPopupWindow(
    view: View?,
    activity: Context?,
    width: Int = ViewGroup.LayoutParams.WRAP_CONTENT,
    height: Int = ViewGroup.LayoutParams.MATCH_PARENT,
    dismissEvent: (() -> Unit)? = null
  ): PopupWindow {
    val popupWindow = PopupWindow(view, height, width)
    popupWindow.isFocusable = true
    popupWindow.isOutsideTouchable = true //不能在没有焦点的时候使用
    popupWindow.setBackgroundDrawable(BitmapDrawable()) //必须要设置背景色
    //设置对话框消失时，背景变亮
    popupWindow.setOnDismissListener {
      backgroundAlpha(activity, 1f) //取消暗背景
      dismissEvent?.invoke()
    }
    return popupWindow
  }

  /**
   * 初始化对话框
   *
   * @param view 自定义布局
   * @param activity 类
   * @return 对话框
   */
  fun initPopupWindow(
    view: View?,
    activity: Context?,
    width: Int = ViewGroup.LayoutParams.WRAP_CONTENT,
    height: Int = ViewGroup.LayoutParams.MATCH_PARENT,
    backgroundDark: Boolean = true,
    dismissEvent: (() -> Unit)? = null
  ): PopupWindow {
    val popupWindow = PopupWindow(view, height, width)
    popupWindow.isFocusable = true
    popupWindow.isOutsideTouchable = true //不能在没有焦点的时候使用
//    if (backgroundDark) {
      popupWindow.setBackgroundDrawable(BitmapDrawable()) //必须要设置背景色
//    }
    //设置对话框消失时，背景变亮
    popupWindow.setOnDismissListener {
      backgroundAlpha(activity, 1f) //取消暗背景
      dismissEvent?.invoke()
    }
    return popupWindow
  }

  /**
   * 显示对话框
   *
   * @param popupWindow 对话框
   * @param parentView 显示父控件
   * @param activity 类
   */
  fun showPopupWindow(
    popupWindow: PopupWindow,
    parentView: View?,
    activity: Context?,
    gravity: Int = Gravity.TOP
  ) {
    //设置背景变暗
    backgroundAlpha(activity, 0.5f)
    popupWindow.showAtLocation(parentView, gravity, 0, 0)
  }

  fun dismissPopupWindow(
    popupWindow: PopupWindow,
    activity: Context?,
  ) {
    popupWindow.dismiss()
    backgroundAlpha(activity, 0.0f)
  }

  /**
   * 设置添加屏幕的背景透明度
   *
   * @param bgAlpha //0.0-1.0 越接近1.0越亮
   */
  fun backgroundAlpha(
    context: Context?,
    bgAlpha: Float
  ) {
    if (context is Activity) {
      val lp = context.window.attributes
      lp.alpha = bgAlpha
//      context.window.addFlags(LayoutParams.FLAG_DIM_BEHIND)
      context.window.attributes = lp
    }
  }
}